package com.genbusiness.logic;

import business.domain.Document;
import business.domain.Response;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.Normalizer;
import java.util.Scanner;
import java.util.regex.Pattern;

/**
 *
 * @author Sevket
 */
public class TextManager {

    private Connection connection = null;
    private int percentSuccess = 40;

    public Connection getConnection() {
        if (connection == null) {
            //Connection BDD
            //String url = "jdbc:mysql://10.67.133.161:3306/";
            String url = "jdbc:mysql://localhost:3306/";
            String dbName = "dico";
            String driver = "com.mysql.jdbc.Driver";
            String userName = "root";
            String password = "";
            try {
                Class.forName(driver).newInstance();
                connection = DriverManager.getConnection(url + dbName, userName, password);
            } catch (Exception ex) {
                System.out.println("Erreur de connexion MySQL: " + ex.getMessage());
            }
            return connection;
        } else {
            return connection;
        }
    }

    public boolean analyseDocument(Document document) throws FileNotFoundException, SQLException, NullPointerException {
        Statement st = getConnection().createStatement();
        //On scanne le fichier.
        Scanner scanner = new Scanner(document.getContent());

        String mot = "";
        int nbMotsText = 0;
        String query1 = "SELECT COUNT(mot) as compte FROM  mots WHERE ";
        StringBuilder sb = new StringBuilder();
        sb.append(query1);
        while (scanner.hasNext()) {
            nbMotsText++;
            mot = scanner.next().toLowerCase().trim();
            if (mot.length() == 1) {
                continue;
            }




            // Gestion des apostrophes.
            String[] splitted = mot.split("'");
            mot = splitted[splitted.length - 1];

            // Gestion des accents
            mot = removeAccent(mot);

            //Gestion des adresses mails, si pas adresse mail, on enleve le point.
            if (!Pattern.matches("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", mot)) {
                mot = mot.replaceAll("\\p{P}", ""); //On enleve les points si ce n'est pas une adresse mail.
            } else {
                nbMotsText--;
            }

            //Prépare la requête SQL
            sb.append(" mot = '");
            sb.append(mot);
            sb.append("' OR");
        }
        sb.delete(sb.length() - 3, sb.length()); //Supprime le dernier OR
        sb.append(";");

        ResultSet res = st.executeQuery(sb.toString());
        res.next();
        int nbMotsFind = res.getInt(1);
        
        double pourcentage = 0;
        //Calcul du pourcentage.
        pourcentage = (double)nbMotsFind / (double)nbMotsText * 100;
        System.out.println(nbMotsFind  + " mots sur " + nbMotsText + " correspondent à la langue française pour un pourcentage total de " + pourcentage + "%");

        document.setValidityPercent((int)pourcentage);

        if (pourcentage > percentSuccess) {
            return true;
        } else {
            return false;
        }

    }


    public String removeAccent(String source) {
        return Normalizer.normalize(source, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "");
    }

    public String getTerroristMail(Document document) throws FileNotFoundException {
        Scanner scanner = new Scanner(document.getContent());
        String mail = null;
        String mot = null;
        while (scanner.hasNext()) {
            mot = scanner.next();
            mot = removeAccent(mot);
            mot = removePonctuation(mot);
            
            if (Pattern.matches("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", mot)) {
                mail = mot;
            }
        }
        System.out.println("Le mail du terroriste est le suivant : " + mail);
        return mail;
    }

    private String removePonctuation(String mot) {
        char c = mot.charAt(0);
        char d = mot.charAt(mot.length()-1);
        if(c == ".".charAt(0) || c == ",".charAt(0))
        {
            mot = mot.substring(1);
        }

        if(d == ".".charAt(0) || d == ",".charAt(0))
        {
            mot = mot.substring(0,mot.length()-1);
        }
        return mot;
    }
}
